﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using LERP.Domain;
using LERP.Domain.Enums;
using LERP.Web.Controllers.ViewModels.CustomerViewModels;
using LERP.Web.Controllers.ViewModels.GoodsViewModels;
using Sharp.Framework;
using Sharp.Framework.Extensions;
using Sharp.Framework.Queries;
using SharpArch.NHibernate.Web.Mvc;

namespace LERP.Web.Controllers
{
    public class CustomerController : BaseController
    {

        private readonly IQuery _query;

        public CustomerController(IQuery query)
        {
             _query = query;
        }

        public ActionResult Jsons()
        {
            var result = _query.FindAll<Customer>()
                .Where(m => m.User == Current && m.Status == DataStatus.Normal)
                .Select(m => new { name =   m.Name, linkman= m.Linkman, parent = m.Parent.Name,grand=m.Parent.Parent.Name, id = m.Id }).
                 ToArray();
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public ActionResult Select(bool all=false)
        {
            var viewName = "SelectAll";
            var query = _query.FindAll<Customer>().Where(m => m.Status == DataStatus.Normal);
            if(!all)
            {
                query = query.Where(m => (m.User == Current || m.User == null));
                viewName = "Select";
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new CustomerViewModel
            {
                Id = m.Id,
                Name = m.Name,
                Level = m.Level,
                Linkman = m.Linkman,
                Mobile = m.Mobile,
                Status = m.Status,
                ParentId = m.Parent != null ? m.Parent.Id : 0
            }).ToList();
            return View(viewName,model);
        }
        /// <summary>
        /// 货品价格配置
        /// </summary>
        /// <param name="id"></param>
        /// <param name="categoryId"></param>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Goods(int id,int? categoryId, string keyword, int page = 1, int size = 12)
        {
          
            var customer = _query.Get<Customer>(id);
            if(null==customer)
            {
                return View("NoFound");
            }
            var ids = new List<int> {id};
            var parentid = 0; 
            var customerName = customer.Name;
            if(null!=customer.Parent)
            {
                customerName = customer.Parent.Name + customerName;
                parentid = customer.Parent.Id;
                ids.Add(customer.Parent.Id);
            }
            if(null!=customer.Parent&&null!=customer.Parent.Parent)
            {
                customerName = customer.Parent.Parent.Name + customerName;
                ids.Add(customer.Parent.Parent.Id);
            }
            var list = _query.FindAll<GoodsPrice>().Where(x =>ids.Contains( x.Customer.Id)).Select(x=>new{
                GoodsId=x.Goods.Id,
               CustomerId= x.Customer.Id,
               x.Price, 
               Level =( x.Customer.Id==id?1:(x.Customer.Id==parentid?2:3))
            }).ToList(); 
            var query = _query.FindAll<Goods>().Where(m => m.Status == DataStatus.Normal);
            if (categoryId.HasValue)
            {
                query = query.Where(m => m.Category.Id == categoryId.Value);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Name.Contains(keyword));
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new CustomerGoodsViewModel
            {
                Id = m.Id,
                Name = m.Name,
                CategoryName =
                    ((null == m.Category)
                         ? string.Empty
                         : m.Category.
                               DictionaryText),
                Gencod = m.Gencod,
                Num = m.Num,
                Price = m.Price,
                Unit = m.SellUnit,
                Volume = m.Volume,
                CustomerPrice = m.Price,
                Level = 0

            }).ToPagedList(page, size);
            foreach (var goods in model)
            {
                if(list.Any(x=>x.GoodsId==goods.Id))
                {
                    var customerGoods = list.Where(x => x.GoodsId == goods.Id).OrderBy(x => x.Level).FirstOrDefault();
                    if (customerGoods != null)
                    {
                        goods.CustomerPrice = customerGoods.Price;
                        goods.Level = customerGoods.Level;
                    }
                }
            }
            ViewBag.GoodsCategorys = GoodsCategorys();
            ViewBag.CustomerName = customerName;
            return View(model);
        }


        /// <summary>
        /// 货品价格配置
        /// </summary>
        /// <param name="id"></param>
        /// <param name="goodsId"></param>
        /// <param name="customerPrice"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Goods(int id,int goodsId, decimal customerPrice)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity =
                        _query.FindAll<GoodsPrice>().FirstOrDefault(x => x.Customer.Id == id && x.Goods.Id == goodsId);
                    if (null == entity)
                    {
                        var goods = _query.Get<Goods>(goodsId);
                        var customer = _query.Get<Customer>(id);

                        entity = new GoodsPrice()
                                     {
                                         Created = DateTime.Now,
                                         Modified = DateTime.Now,
                                         Goods = goods,
                                         Customer = customer
                                     };

                    }
                    entity.Price = customerPrice;
                    _query.Save(entity);
                }
            }
            catch
            {
                return View("Error");
            }
            return RedirectToAction("Goods");
        }
        /// <summary>
        /// 取消货品价格
        /// </summary>
        /// <param name="id"></param>
        /// <param name="goodsId"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns> 
        [Transaction]
        public ActionResult DeleteGoodsPrice(int id, int goodsId, string returnUrl)
        {
            try
            {

                var entity =
                    _query.FindAll<GoodsPrice>().FirstOrDefault(x => x.Customer.Id == id && x.Goods.Id == goodsId);
                if (null != entity)
                {
                    _query.Delete(entity); 
                }
            }
            catch
            {
                return View("Error");
            }
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Goods");
            }
            return Redirect(returnUrl);
        }

        /// <summary>
        /// 获取货品分类列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GoodsCategorys()
        {
            var list = _query.FindAll<GoodsCategory>().Where(m => m.Stauts == DataStatus.Normal).Where(m => m.Parent != null);
            return list.OrderBy(m => m.Parent.Id).Select(x => new SelectListItem { Text = string.Format("{0}--{1}", x.Parent.DictionaryText, x.DictionaryText), Value = x.Id.ToString() }).ToList();
        }
        /// <summary>
        /// 获取客户列表Goods
        /// </summary> 
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            var query = _query.FindAll<Customer>().Where(m => m.Status == DataStatus.Normal);
            var model = query.OrderByDescending(m => m.Modified).Select(m => new CustomerViewModel
            {
                Id = m.Id,
                Name = m.Name,
                Level = m.Level,
                Linkman = m.Linkman,
                Mobile = m.Mobile,
                Status = m.Status,
                ParentId = m.Parent!=null?m.Parent.Id:0
            }).ToList();
            return View(model);
        } 
        /// <summary>
        /// 客户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Details(int id)
        {
            var model = _query.Get<Customer>(id);
            if (null == model)
            {
                return View("NoFound");
            }
            return View(model);
        }


        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        private List<SelectListItem> GetCustomers(CustomerLevel level)
        {
            switch (level)
            {
                case CustomerLevel.First:
                    return _query.FindAll<Customer>().Where(x => x.Status == DataStatus.Normal && x.Level == CustomerLevel.First).Select(
                m => new SelectListItem { Text = m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture) }).
                          ToList();
                case CustomerLevel.Second:
                    return _query.FindAll<Customer>().Where(x => x.Status == DataStatus.Normal && x.Level == CustomerLevel.Second).Select(
                m => new SelectListItem { Text = m.Parent.Name + "-" + m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture) }).
                          ToList();
                case CustomerLevel.Third:
                    return _query.FindAll<Customer>().Where(x => x.Status == DataStatus.Normal && x.Level == CustomerLevel.Third).Select(
                m => new SelectListItem { Text = m.Parent.Parent.Name + "-" + m.Parent.Name + "-" + m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture) }).
                          ToList();
            }
            return null;
        }

        /// <summary>
        /// 获取员工
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetUsers()
        {
            return _query.FindAll<User>().Where(x => x.Stauts == DataStatus.Normal && x.Role == UserRole.User).Select(
               m => new SelectListItem { Text = m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture) }).
                         ToList();
        }

        /// <summary>
        /// 创建父级客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateFirst()
        { 
            return View(new CreateFirstCustomerViveModel());
        } 

        /// <summary>
        /// 提交 创建父级客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult CreateFirst(CreateFirstCustomerViveModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Customer
                        {
                            Status = DataStatus.Normal,
                            Created = DateTime.Now,
                            Modified = DateTime.Now,
                            Level = CustomerLevel.First,
                            Name = model.Name,
                            Linkman = model.Linkman,
                            Email = model.Email,
                            Mobile = model.Mobile,
                            Fax = model.Fax,
                            Remark = model.Remark
                        };
                    _query.Save(entity);
                    return RedirectToAction("Index", "Customer");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            } 
            return View(model);
        }



        /// <summary>
        /// 创建子级客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateSecond(int parentId)
        {
            ViewBag.Parents = GetCustomers(CustomerLevel.First);
            return View(new CreateSecondCustomerViveModel{ParentId = parentId});
        }
        /// <summary>
        /// 提交 创建子级客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult CreateSecond(CreateSecondCustomerViveModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {

                   var parent = _query.Get<Customer>(model.ParentId);
                    var entity = new Customer
                    {
                        Status = DataStatus.Normal,
                        Created = DateTime.Now,
                        Modified = DateTime.Now,
                        Level = CustomerLevel.Second,
                        Name = model.Name,
                        Linkman = model.Linkman,
                        Email = model.Email,
                        Mobile = model.Mobile,
                        Fax = model.Fax,
                        Remark = model.Remark,
                        Parent = parent
                    };
                    _query.Save(entity);
                    return RedirectToAction("Index", "Customer");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            } 
            ViewBag.Parents = GetCustomers(CustomerLevel.First);
            return View(model);
        }


        /// <summary>
        /// 创建孙级客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateThird(int parentId)
        {
            ViewBag.Parents = GetCustomers(CustomerLevel.Second);
            ViewBag.Users = GetUsers();
            return View(new CreateThirdCustomerViveModel{ParentId = parentId});
        }

        /// <summary>
        /// 提交 创建孙级客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult CreateThird(CreateThirdCustomerViveModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {

                    var parent = _query.Get<Customer>(model.ParentId);
                    var user = _query.Get<User>(model.UserId);
                    var entity = new Customer
                        {
                            Status = DataStatus.Normal,
                            Created = DateTime.Now,
                            Modified = DateTime.Now,
                            Level = CustomerLevel.Third,
                            Name = model.Name,
                            Linkman = model.Linkman,
                            Email = model.Email,
                            Mobile = model.Mobile,
                            Fax = model.Fax,
                            Remark = model.Remark,
                            Parent = parent,
                            User = user,
                            Province = model.Province,
                            City = model.City,
                            Address = model.Address,
                            Days = model.Days,
                            OnceFreight = model.OnceFreight,
                            UnitFreight = model.UnitFreight
                        };
                    _query.Save(entity);
                    return RedirectToAction("Index", "Customer");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            ViewBag.Users = GetUsers();
            ViewBag.Parents = GetCustomers(CustomerLevel.Second);
            return View(model);
        }

        /// <summary>
        /// 修改货品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id)
        {
            var model = _query.Get<Customer>(id);
            if (null == model)
            {
                return View("NoFound");
            }

            ViewBag.Users = GetUsers();
            switch (model.Level)
            {
                case CustomerLevel.First:
                    var customer = new CreateFirstCustomerViveModel
                                       {
                                           Name = model.Name,
                                           Linkman = model.Linkman,
                                           Email = model.Email,
                                           Mobile = model.Mobile,
                                           Fax = model.Fax,
                                           Remark = model.Remark
                                       };
                    return View("EditFirst", customer);
                case CustomerLevel.Second:
                    var customer1 = new CreateSecondCustomerViveModel
                                        {
                                            Name = model.Name,
                                            Linkman = model.Linkman,
                                            Email = model.Email,
                                            Mobile = model.Mobile,
                                            Fax = model.Fax,
                                            Remark = model.Remark,
                                            ParentId = model.Parent.Id
                                        };
                    ViewBag.Parents = GetCustomers(CustomerLevel.First);
                    return View("EditSecond", customer1);
                case CustomerLevel.Third:
                    var customer2 = new CreateThirdCustomerViveModel
                                        {
                                            Name = model.Name,
                                            Linkman = model.Linkman,
                                            Email = model.Email,
                                            Mobile = model.Mobile,
                                            Fax = model.Fax,
                                            Remark = model.Remark,
                                            ParentId = model.Parent.Id,
                                            Address = model.Address,
                                            City = model.City,
                                            Province = model.Province,
                                            UserId = model.User.Id,
                                            Days = model.Days,
                                            OnceFreight = model.OnceFreight,
                                            UnitFreight = model.UnitFreight
                                        };
                    ViewBag.Parents = GetCustomers(CustomerLevel.Second);
                    return View("EditThird", customer2);

            }
            return View("NoFound");
        }

        /// <summary>
        /// 修改客户 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult EditFirst(int id, CreateFirstCustomerViveModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var entity = _query.Get<Customer>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }  
                    entity.Modified = DateTime.Now; 
                    entity.Name = model.Name;
                    entity.Linkman = model.Linkman;
                    entity.Email = model.Email;
                    entity.Mobile = model.Mobile;
                    entity.Fax = model.Fax;
                    entity.Remark = model.Remark;

                    _query.Save(entity);
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            } 
            return View();
        }


        /// <summary>
        /// 修改客户 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult EditSecond(int id, CreateSecondCustomerViveModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var entity = _query.Get<Customer>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }
                    entity.Modified = DateTime.Now;

                    var parent = _query.Get<Customer>(model.ParentId);  
                    entity.Name = model.Name;
                    entity.Linkman = model.Linkman;
                    entity.Email = model.Email;
                    entity.Mobile = model.Mobile;
                    entity.Fax = model.Fax;
                    entity.Remark = model.Remark;
                    entity.Parent = parent;

                    _query.Save(entity);
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            return View();
        }


        /// <summary>
        /// 修改客户 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult EditThird(int id, CreateThirdCustomerViveModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var entity = _query.Get<Customer>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }
                    entity.Modified = DateTime.Now;

                    var parent = _query.Get<Customer>(model.ParentId);
                    var user = _query.Get<User>(model.UserId); 
                    entity.Name = model.Name;
                    entity.Linkman = model.Linkman;
                    entity.Email = model.Email;
                    entity.Mobile = model.Mobile;
                    entity.Fax = model.Fax;
                    entity.Remark = model.Remark;
                    entity.Parent = parent;
                    entity.User = user;
                    entity.Province = model.Province;
                    entity.City = model.City;
                    entity.Address = model.Address;
                    entity.Days = model.Days;
                    entity.OnceFreight = model.OnceFreight;
                    entity.UnitFreight = model.UnitFreight;

                    _query.Save(entity);
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            return View();
        }

        [Transaction]
        [HttpGet]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<Customer>(id);

            if (null == entity)
            {
                return View("NoFound");
            }
            entity.Status = DataStatus.Deleted;
            _query.Save(entity);
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index");
            }
            return Redirect(returnUrl);
        }
    }
}
